package com.yc.thread.basic;

import java.util.concurrent.*;

/**
 * 带返回值的任务类
 * @author zwei
 * @create 2024-07-14 10:14
 */
public class Test4_callable_FutureTask {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        //方式1：内部类
        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            //任务功能：累加和
            @Override
            public Integer call() throws Exception {
                int count = 0;
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(1000);
                    count += i;
//                    if (i==10){
//                        throw new RuntimeException("error");
//                    }
                }
                return count;
            }
        });
        Thread t1 = new Thread(task);
        t1.start();
        //方式二：lambda写法:     函数式写法
        FutureTask<Integer> task2=new FutureTask<>(    ()->{
            int count = 0;
            for (int i = 0; i < 10; i++) {
                Thread.sleep(1000);
                count += i;
//                    if (i==10){
//                        throw new RuntimeException("error");
//                    }
            }
            return count;
        });
        Thread t2=new Thread(task2);
        t2.start();


        //有返回值
        System.out.println("累加和为："+task2.get());
        System.out.println("累加和为：" + task.get());
        System.out.println("请理解什么是阻塞式。。。");
    }
}
